package com.ozo.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.easy.entity.SysRole;
import com.ozo.easy.entity.SysUserRole;
import com.ozo.easy.mapper.SysRoleMapper;
import com.ozo.easy.mapper.SysUserRoleMapper;
import com.ozo.easy.pojo.dto.SysUserRoleAuthDTO;
import com.ozo.easy.pojo.vo.SysRoleVO;
import com.ozo.easy.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色 服务实现类
 *
 * @author ozo
 * @version 1.0
 * @date 2025-02-17 16:53:43
 */
@RequiredArgsConstructor
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    private final SysRoleMapper sysRoleMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void auth(SysUserRoleAuthDTO roleAuthDTO) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, roleAuthDTO.getUserId());
        baseMapper.delete(queryWrapper);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(roleAuthDTO.getUserId());
        sysUserRole.setRoleId(roleAuthDTO.getRoleId());
        baseMapper.insert(sysUserRole);
    }

    @Override
    public List<SysRoleVO> detail(Long id) {
        List<SysRole> recordList = sysRoleMapper.selectList(new LambdaQueryWrapper<>());

        LambdaQueryWrapper<SysUserRole> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(SysUserRole::getUserId, id);
        List<Long> roleIdList = baseMapper.selectList(queryWrapper1).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        List<SysRoleVO> recordVOList = BeanUtil.copyToList(recordList, SysRoleVO.class);
        for (SysRoleVO sysRoleVO : recordVOList) {
            sysRoleVO.setSelected(roleIdList.contains(sysRoleVO.getId()));
        }

        return recordVOList;
    }
}
